package com.sixbro.api.docs.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

/**
 * <p>
 *  An example of explicitly configuring Spring Security with the defaults.
 * </p>
 *
 * @Author: Mr.Lu
 * @Since: 2022/1/7 15:19
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // Customize the application security ...
        //http.requiresChannel().anyRequest().requiresSecure();
        http
                .authorizeRequests((authorize) -> authorize
                        .antMatchers("/swagger-ui/**", "/swagger-resources/**", "/v2/api-docs", "/v3/api-docs", "/webjars/**").permitAll()
                        .antMatchers("/api/**").permitAll()
                        .anyRequest().authenticated()
                )
                .httpBasic(withDefaults())
                .formLogin(withDefaults());
        return http.build();
    }

//    /**
//     * 如果你使用的版本是Spring Security 5.4，你可以这么定制WebSecurity:
//     * @return
//     */
//    @Bean
//    WebSecurityCustomizer swaggerWebSecurityCustomizer() {
//        return (web) -> {
//            web.ignoring().antMatchers(new String[]{"/swagger-ui/**", "/swagger-resources/**", "/v2/api-docs", "/v3/api-docs", "/webjars/**"});
//        };
//    }



//    @Bean
//    public CorsConfigurationSource corsConfigurationSource() {
//
//        final CorsConfiguration configuration = new CorsConfiguration();
//        configuration.setMaxAge(3600L);
//
//        configuration.setAllowedOrigins(Collections.singletonList("*"));
//        configuration.setAllowedMethods(Collections.singletonList("*"));
//        configuration.setAllowCredentials(true);
//        configuration.setAllowedHeaders(Collections.singletonList("*"));
//        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/api/**", configuration);
//
//        return source;
//    }

}
